
#include <string>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <cstring>
 #include <arpa/inet.h>
 #include <iostream>
  #include <unistd.h>
  #include "protocol.hpp"

 using namespace std;
 using namespace Protocol;

int main(int argc, char** argv)
{
    if(argc!= 3) return -1;
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family= AF_INET;
    server.sin_addr.s_addr= inet_addr(argv[1]);
    server.sin_port= htons(stoi(argv[2]));   //BUG--没有转成网络字节序

    int sockfd= socket(AF_INET, SOCK_STREAM, 0);

    connect(sockfd, (struct sockaddr*)&server, sizeof(server));

    string s;
    char buffer[1024];
    int flag=1;
    while(flag)
    {
        cout<<"请输入：";
        int x,y;
        char op;
        cin>>x>>op>>y;

        Request req(x,y,op);

        string sen=req.Serialize();
        EnLenHeader(sen);
        
        write(sockfd, sen.c_str(), sen.size());


        while(1)
        {
            int n= read(sockfd, buffer, sizeof(buffer));
            if(n> 0)
            {
                buffer[n]= 0;

                s+=buffer;

                string tmp;
                if(DeLenHeader(s, &tmp))
                {
                    Response resp;
                    resp.DeSerialize(tmp);

                    cout<<"结果："<<resp._result<<"响应码："<<resp._code<<endl;
                    break;
                }
            }
            else if(n==0)
            {
                cout<<"连接断开"<<endl;
                flag=0;
                break;
            }

        }
        
        
    }

    close(sockfd);


    return 0;
}